package mygame.Collision;

import java.nio.FloatBuffer;

import com.jme3.math.Vector3f;
import com.jme3.scene.Geometry;
import com.jme3.scene.Mesh;
import com.jme3.scene.VertexBuffer.Type;

public class FindCollidingVertex {
	private Geometry geom;
	private Mesh mesh;
	private Vector3f hitPoint;
	private Vector3f center;
	
	public FindCollidingVertex(Geometry geom, Vector3f hitPoint) {
		this.geom = geom;
		this.mesh = geom.getMesh();
		this.hitPoint = hitPoint;
        this.center = geom.getLocalTranslation();
	}
	
	private int findIndex(FloatBuffer buf){
         int savePos = buf.limit();         
         int pos = 0;
         float dist = -1;
         int targetIndex = -1;
         
         while(pos<savePos){
         	float[] temp = new float[3];
         	temp[0] = buf.get(pos)+center.x;
         	temp[1] = buf.get(pos+1)+center.y;
         	temp[2] = buf.get(pos+2)+center.z;
         	Vector3f v = geom.getLocalRotation().mult(new Vector3f(temp[0],temp[1],temp[2]));
         	float dt = v.distance(this.hitPoint);
         	if(dist < 0 || dt <dist){
         		dist = dt;
         		targetIndex = pos;
         	}
         	pos+=3;
         }
         return targetIndex;        
	}
	
	public void increaseY(float incr){
		FloatBuffer buf = mesh.getFloatBuffer(Type.Position); 
		buf.rewind();
		
		int targetIndex = findIndex(buf);
		
		float yVal = buf.get(targetIndex+1)+incr;
        buf.position(targetIndex);
        buf.put(targetIndex, yVal);
        
        mesh.setBuffer(Type.Position, 3, buf);
        mesh.updateBound();
	}
	
	public void increaseVolume(float incr){
		FloatBuffer buf = mesh.getFloatBuffer(Type.Position); 
		buf.rewind();
				
		int targetIndex = findIndex(buf);
		float xVal = (buf.get(targetIndex))*(1+incr);
		float yVal = (buf.get(targetIndex+1))*(1+incr);
		float zVal = (buf.get(targetIndex+2))*(1+incr);
				
		buf.put(targetIndex, xVal);
		buf.put(targetIndex+1, yVal);
		buf.put(targetIndex+2, zVal);
		
		mesh.setBuffer(Type.Position, 3, buf);
        mesh.updateBound();
	}
	
	public static void incrY(Geometry geom, Vector3f hitPoint,float incr){
		FindCollidingVertex cV = new FindCollidingVertex(geom, hitPoint);
		cV.increaseY(incr);
	}
	
	public static void incrVol(Geometry geom, Vector3f hitPoint,float incr){
		FindCollidingVertex cV = new FindCollidingVertex(geom, hitPoint);
		cV.increaseVolume(incr);
	}
	
}
